package com.example.websocket.channel;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class SelectorTest {

    private Selector selector = null;

    private Map<String, SelectionKey> map = new HashMap<>();

    private Charset charset = Charset.forName("GBK");

    private ByteBuffer buffer = ByteBuffer.allocate(1024);

    private static final int PORT = 3001;

    public void init() throws IOException {
        selector = Selector.open();

        ServerSocketChannel server = ServerSocketChannel.open();

        server.socket().bind(new InetSocketAddress("127.0.0.1", PORT));

        server.configureBlocking(false);

        server.register(selector, SelectionKey.OP_ACCEPT);
        while (selector.select() > 0) {
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while (it.hasNext()) {
                SelectionKey sk = it.next();
                if (sk.isAcceptable()) {
                    SocketChannel socketChannel = server.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    System.out.println(socketChannel.getRemoteAddress().toString());
                    sk.interestOps(SelectionKey.OP_ACCEPT);
                }
                if (sk.isReadable()) {
                    SocketChannel sc = (SocketChannel) sk.channel();
                    String content = "";
                    try {
                        while (sc.read(buffer) > 0) {
                            buffer.flip();
                            content += charset.decode(buffer);
                            System.out.println("==============读取的数据是：" + content);
                            sk.interestOps(SelectionKey.OP_READ|SelectionKey.OP_WRITE);
                            if (content.equals("login")) {
                                map.put(sc.getRemoteAddress().toString(), sk);
                            } else {
                                JSONObject object = JSON.parseObject(content);
                                String address = object.getString("address");
                                String msg = object.getString("message");
                                msg = sc.getRemoteAddress() + "说：" + msg;
                                send(address, msg);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        sk.cancel();
                        if (sk.channel() != null) {
                            sk.channel().close();
                        }
                    }
                    if (content.length() > 0) {
                        sk.attach(content);
                    }
                    buffer.clear();
                }
//                if (sk.isValid() && sk.isWritable()) {
//                    SocketChannel sc = (SocketChannel) sk.channel();
//                    System.out.println(sc.getRemoteAddress());
//                    String content = (String) sk.attachment();
//                    sc.write(charset.encode(content));
//                    sk.interestOps(SelectionKey.OP_READ);
//                }
                it.remove();
            }

        }
    }

    public void send(String address, String str) {
        SelectionKey sk = map.get(address);
        System.out.println(sk.isValid());
        System.out.println(sk.isWritable());
        try {
            if (sk.isValid() && sk.isWritable()) {
                SocketChannel sc = (SocketChannel) sk.channel();
                sc.write(charset.encode(str));
                sk.interestOps(SelectionKey.OP_READ);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            new SelectorTest().init();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
